const { program } = require('commander');
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 默认配置
const DEFAULT_CONFIG = {
  host: '127.0.0.1',
  port: 8080,
  user: 'zs',
  pwd: 'ddd'
};

// 命令行参数配置
program
  .option('--host <host>', '服务器主机地址，默认为 127.0.0.1', DEFAULT_CONFIG.host)
  .option('--port <port>', '服务器端口，默认为 8080', DEFAULT_CONFIG.port)
  .option('--user <user>', '用户名，默认为 zs', DEFAULT_CONFIG.user)
  .option('--pwd <pwd>', '密码，默认为 ddd', DEFAULT_CONFIG.pwd)
  .helpOption('--help', '显示帮助信息')
  .on('--help', () => {
    console.log('');
    console.log('示例:');
    console.log('  $ node client/index.js --host=localhost --port=8080 --user=zs --pwd=ddd');
    console.log('  $ node client/index.js --user=ls --pwd=ddd');
    console.log('  $ node client/index.js --help');
  })
  .parse(process.argv);

const options = program.opts();

// 创建axios实例
const api = axios.create({
  baseURL: `http://${options.host}:${options.port}/api`,
  timeout: 5000
});

let token = null;
let currentLocalDir = process.cwd();
let currentRemoteDir = '';

// 登录函数
async function login() {
  try {
    const response = await api.post('/login', {
      username: options.user,
      password: options.pwd
    });
    token = response.data.token;
    api.defaults.headers.common['Authorization'] = token;
    return true;
  } catch (error) {
    console.error('登录失败:', error.response?.data?.error || error.message);
    return false;
  }
}

// 命令处理函数
const commands = {
  async upload(args) {
    if (args.length !== 1) {
      console.error('用法: upload <file>');
      return;
    }

    const filePath = path.join(currentLocalDir, args[0]);
    if (!fs.existsSync(filePath)) {
      console.error('文件不存在');
      return;
    }

    const formData = new FormData();
    formData.append('file', fs.createReadStream(filePath));

    try {
      await api.post('/upload', formData, {
        headers: formData.getHeaders()
      });
      console.log('文件上传成功');
    } catch (error) {
      console.error('上传失败:', error.response?.data?.error || error.message);
    }
  },

  async download(args) {
    if (args.length !== 1) {
      console.error('用法: download <file>');
      return;
    }

    try {
      const response = await api.get(`/download/${args[0]}`, {
        responseType: 'stream'
      });
      const writer = fs.createWriteStream(path.join(currentLocalDir, args[0]));
      response.data.pipe(writer);
      writer.on('finish', () => console.log('文件下载成功'));
    } catch (error) {
      console.error('下载失败:', error.response?.data?.error || error.message);
    }
  },

  async delete(args) {
    if (args.length !== 1) {
      console.error('用法: delete <file/dir>');
      return;
    }

    try {
      await api.delete(`/delete/${args[0]}`);
      console.log('删除成功');
    } catch (error) {
      console.error('删除失败:', error.response?.data?.error || error.message);
    }
  },

  async rename(args) {
    if (args.length !== 2) {
      console.error('用法: rename <old-name> <new-name>');
      return;
    }

    try {
      await api.post('/rename', {
        oldName: args[0],
        newName: args[1]
      });
      console.log('重命名成功');
    } catch (error) {
      console.error('重命名失败:', error.response?.data?.error || error.message);
    }
  },

  async mkdir(args) {
    if (args.length !== 1) {
      console.error('用法: mkdir <dir>');
      return;
    }

    try {
      await api.post('/mkdir', { dirName: args[0] });
      console.log('目录创建成功');
    } catch (error) {
      console.error('创建目录失败:', error.response?.data?.error || error.message);
    }
  },

  async list() {
    try {
      const response = await api.get('/list');
      console.log('\n当前目录内容:');
      response.data.files.forEach(file => {
        console.log(`${file.name}\t${file.size}字节\t${file.mtime}`);
      });
    } catch (error) {
      console.error('获取目录列表失败:', error.response?.data?.error || error.message);
    }
  },

  async lcd(args) {
    if (args.length !== 1) {
      console.error('用法: lcd <dir>');
      return;
    }

    try {
      const newPath = path.resolve(args[0]);
      if (fs.existsSync(newPath)) {
        currentLocalDir = newPath;
        console.log('本地目录已更改为:', currentLocalDir);
      } else {
        console.error('目录不存在');
      }
    } catch (error) {
      console.error('更改本地目录失败:', error.message);
    }
  },

  lpwd() {
    console.log('当前本地目录:', currentLocalDir);
  },

  async rcd(args) {
    if (args.length !== 1) {
      console.error('用法: rcd <dir>');
      return;
    }

    try {
      await api.post('/cd', { path: args[0] });
      const response = await api.get('/pwd');
      currentRemoteDir = response.data.currentDir;
      console.log('远程目录已更改为:', currentRemoteDir);
    } catch (error) {
      console.error('更改远程目录失败:', error.response?.data?.error || error.message);
    }
  },

  async rpwd() {
    try {
      const response = await api.get('/pwd');
      console.log('当前远程目录:', response.data.currentDir);
    } catch (error) {
      console.error('获取远程目录失败:', error.response?.data?.error || error.message);
    }
  }
};

// 修改main函数
async function main() {
  if (!(await login())) {
    process.exit(1);
  }

  console.log('登录成功！输入 help 查看可用命令');

  rl.on('line', async (input) => {
    const [cmd, ...args] = input.trim().split(' ');

    if (cmd === 'exit') {
      rl.close();
      return;
    }

    if (cmd === 'help') {
      console.log(`
可用命令:
  upload <file>                  - 上传文件
  download <file>               - 下载文件
  delete <file/dir>             - 删除文件或目录
  rename <old-name> <new-name>  - 重命名文件或目录
  mkdir <dir>                   - ��建目录
  list                         - 显示当前目录内容
  lcd <dir>                    - 更改本地目录
  lpwd                         - 显示当前本地目录
  rcd <dir>                    - 更改远程目录
  rpwd                         - 显示当前远程目录
  help                         - 显示此帮助
  exit                         - 退出程序
      `);
      return;
    }

    const handler = commands[cmd];
    if (handler) {
      await handler(args);
    } else {
      console.error('未知命令。输入 help 查看可用命令。');
    }

    rl.prompt();
  });

  rl.prompt();
}

main(); 